<?php


namespace common\drivers\spiderProduct;


use common\drivers\interfaces\SpiderProductInterface;

class pddSpider extends BaseSpider implements SpiderProductInterface
{
    /**
     * 抓取的商品信息格式
     * @var array
     */
    protected $productInfo = [
        //'mall_id' => '',//店铺ID
        //'goods_id' => '',//商品ID
        //'goods_name' => '', //标题信息
        //'cat_id' => '', //叶子类目ID
        //'carousel_gallery_list' => [],//商品轮播图列表
        //'goods_desc' => '',//商品描述
        //'image_url' => '',//商品主图
        //'market_price' => '',//市场价格，单位为分
        //'status' => '',//商品状态 1:上架，2：下架，3：售罄 4：已删除
        'sku_list' => [],//SKU
        'video_gallery' => [],//商品视频
        'tiny_name' => '',//短标题
        'goods_property_list' => [],//商品属性信息
        'detail_gallery_list' => [],//商品详情图
    ];

    /**
     * 抓取商品信息字段转换
     */
    protected $transSpiderColumnInfo = [
        'mall_id' => 'mallID',//店铺ID
        'cat_id' => 'catID',//
        'goods_id' => 'goodsID',//
        'goods_name' => 'goodsName',//
        'goods_desc' => 'shareDesc',//
        'image_url' => 'hdThumbUrl',//
        'market_price' => 'minNormalPrice',//
        'carousel_gallery_list' => 'viewImageData',//
        'status' => 'status',//
    ];

    /**
     * 获取地址资源
     * @return string
     */
    public function getContents(string $url, $params = []): string
    {
        $resources = $this->spiderContent($url, $params);
        $this->resources = $resources;
        return $this->resources;
    }


    /**
     * 处理采集下来的内容
     * @return array
     */
    public function formatContents(): array
    {
        preg_match("/window.rawData=(.*\s*?)<\/script>/", $this->resources, $match1);
        $json = $match1[1] ?? '';
        $json = substr(trim($json), 0, -1);
        $data = $json ? json_decode($json, true) : [];
        $good = $data['store']['initDataObj']['goods'] ?? [];
        if (!$good) {
            $this->setErrorInfo('请登录后操作');
            return [];
        }
        foreach ($this->transSpiderColumnInfo as $pdd_column => $spider_column) {
            $this->productInfo[$pdd_column] = $good[$spider_column] ?? '';
        }
        $this->setDetailGalleryList($good);
        $this->setVideoGallery($good);
        $this->setSkuList($good);
        $this->setGoodsPropertyList($good);
        ksort($this->productInfo);
        return $this->productInfo;
    }

    public function setGoodsPropertyList($good)
    {
        $attrs = $good['goodsProperty'] ?? [];
        $return = [];
        foreach ($attrs as $attr) {
            $return[] = [
                'punit' => $attr['key'] ?? '',//属性单位
                'ref_pid' => $attr['ref_pid'] ?? '',//引用属性id
                'template_pid' => '',//模板属性Id
                'vid' => '',//基础属性值Id
                'vvalue' => isset($attr['values']) ? implode(",", $attr['values']) : '',//基础属性值
            ];
        }
        $this->productInfo['goods_property_list'] = $return;
    }

    public function setSkuList($good)
    {
        $skus = $good['skus'] ?? [];
        $return = [];
        foreach ($skus as $sku) {
            $specs = $sku['specs'] ?? [];
            $_specs = [];
            $specifications = [];
            foreach ($specs as $spec) {
                $spec_name = $spec['spec_value'] ?? '';
                $_specs[] = [
                    'parent_id' => '',//自定义规格所属的规格ID
                    'parent_name' => $spec['spec_key'] ?? '',//商品规格ID对应的规格名称
                    'spec_id' => $spec['spec_key_id'] ?? '',//自定义规格ID
                    'spec_name' => $spec_name,//自定义规格名称
                ];
                $spec_name && $specifications[] = $spec_name;
            }
            $return[] = [
                'is_onsale' => $sku['isOnsale'] ?? 1,//默认上架
                'length' => '',//sku送装参数：长度
                'limit_quantity' => $sku['limitQuantity'] ?? '',//sku购买限制
                'multi_price' => '',//商品团购价格 单位分
                'out_sku_sn' => '',//商家编码
                'out_source_sku_id' => '',//第三方sku Id
                'oversea_sku' => [
                    'measurement_code' => '',//计量单位编码
                    'specifications' => $specifications ? implode(",", $specifications) : '',//规格
                    'taxation' => '',//税费
                ],
                'price' => isset($sku['normalPrice']) ? $this->moneyToFen($sku['normalPrice']) : 0,//商品单买价格 单位分
                'quantity' => $sku['quantity'] ?? 0,//库存
                'reserve_quantity' => '',//预扣库存
                'sku_id' => $sku['skuId'] ?? '',
                'spec' => $_specs,
                'thumb_url' => $sku['thumbUrl'] ?? '',
                'weight' => $sku['weight'] ?? '',
            ];
        }
        $this->productInfo['sku_list'] = $return;
    }

    public function setVideoGallery($good)
    {
        $videoGallery = $good['videoGallery'] ?? [];
        foreach ($videoGallery as $video) {
            $video_url = $video['videoUrl'] ?? '';
            if ($video_url) {
                $this->productInfo['video_gallery'][] = ['file_id' => 0, 'video_url' => $video_url];
            }
        }
    }

    public function setDetailGalleryList($good)
    {
        $list = $good['detailGallery'] ?? [];
        foreach ($list as $_list) {
            $image_url = $_list['url'] ?? '';
            if ($image_url) {
                $this->productInfo['detail_gallery_list'][] = $image_url;
            }
        }
    }

    public function moneyToFen($money)
    {
        return $money * 100;
    }

    /**
     * 查询错误信息
     * @return array
     */
    public function getErrorInfo()
    {
        return $this->errorInfo;
    }


    /**
     * 设置错误信息
     * @param string $msg
     * @return mixed
     */
    public function setErrorInfo(string $msg = '')
    {
        $this->errorInfo['needLogin'] = '请登录后操作';
    }

    /**
     * save db
     * @return mixed|void
     */
    public function saveDb()
    {
        // TODO: Implement saveDb() method.
    }
}